package com.starblink.brand.ui

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.fragment.BaseTVMFragment
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.SubscribeBrandEvent
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.basic.style.view.recyclerview.SimpleGapItemDecor
import com.starblink.brand.adapter.BrandAllCell
import com.starblink.brand.adapter.BrandAllTitleCell
import com.starblink.brand.adapter.BrandDecorCell
import com.starblink.brand.adapter.BrandLetterCell
import com.starblink.brand.bean.BrandAllBean
import com.starblink.brand.bean.BrandAllTitleBean
import com.starblink.brand.databinding.CellBrandAllBinding
import com.starblink.brand.databinding.CellBrandAllTitleBinding
import com.starblink.brand.databinding.CellBrandItemdecorBinding
import com.starblink.brand.databinding.CellBrandLetterBinding
import com.starblink.brand.databinding.FragmentAllBinding
import com.starblink.brand.model.BrandAllVM

class AllFragment : BaseTVMFragment<FragmentAllBinding,BrandAllVM>() , AllLetterI {
    lateinit var rvBrandAllLayoutManager: LinearLayoutManager
    lateinit var rvLetterLayoutManager: LinearLayoutManager
    var firstVisibleItem:Int=0 //第一个可见的item位置
    companion object {
        fun obtainFragment(): AllFragment {
            return AllFragment()
        }
    }

    private val brandAllAdapter by lazyOnNone {
        MutableAdapter(viewModel.brandAllList.value!!).apply {
            addVhDelegate {
                BrandAllCell(CellBrandAllBinding.inflate(layoutInflater,it,false)){ brandId ->
                    brandId in viewModel.subscribeList
                }
            }
            addVhDelegate {
                BrandAllTitleCell(CellBrandAllTitleBinding.inflate(layoutInflater,it,false))
            }
            addVhDelegate {
                BrandDecorCell(CellBrandItemdecorBinding.inflate(layoutInflater,it,false))
            }
        }
    }
    //字母
    private val letterAdapter by lazyOnNone {
        MutableAdapter(viewModel.brandLetterList.value!!).apply {
            addVhDelegate {
                BrandLetterCell(CellBrandLetterBinding.inflate(layoutInflater,it,false),this@AllFragment)
            }
        }
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentAllBinding {
        return FragmentAllBinding.inflate(inflater, container, false)
    }

    override fun startObserve() {
        FlowBus.with<Boolean>(FlowConst.LOGIN_STATUS_CHANGE).register(this) {
            viewModel.reqFetchSubBrandList()
            viewModel.reqFetchTopBrandFullList()
        }

        viewModel.brandAllList.observe(this) {
            brandAllAdapter.notifyDataSetChanged()

            viewBinding.layoutBrandTitle.tvAllBrandTitle.visibleOrGone(it.isNotEmpty()){
                changeLetterTitle(0)
            }
        }
        viewModel.brandLetterList.observe(this){
            letterAdapter.notifyDataSetChanged()
        }

        FlowBus.with<SubscribeBrandEvent>(FlowConst.SUBSCRIBE_BRAND_EVENT).register(this) { event ->

            if(event.hasSub && event.brandId !in viewModel.subscribeList){
                viewModel.subscribeList.add(event.brandId)
            }
            if(!event.hasSub && event.brandId in viewModel.subscribeList){
                viewModel.subscribeList.remove(event.brandId)
            }
            viewModel.brandAllList.value?.forEachIndexed { index, item ->
                if(item is BrandAllBean){
                    item.brandFList?.forEach { it ->
                        if(event.brandId == it.topBrandInfoVOF.brandId ){
                            brandAllAdapter.notifyItemRangeChanged(index,1)
                        }
                    }
                }
            }


        }
    }

    override fun initData() {
//        rvBrandAllLayoutManager = viewBinding.rvAllBrand.bindProductFeeds(brandAllAdapter, spanCount =1,horGap = 0, verGap = 20) as WrapStaggeredGridLayoutManager

        rvBrandAllLayoutManager = LinearLayoutManager(requireContext())
        viewBinding.rvAllBrand.layoutManager = rvBrandAllLayoutManager
        viewBinding.rvAllBrand.adapter = brandAllAdapter
        viewBinding.rvAllBrand.addItemDecoration(
            SimpleGapItemDecor(
                horGap = 0.dp2px(),
                verGap = 20.dp2px()
            )
        )

        rvLetterLayoutManager= LinearLayoutManager(requireContext())
        viewBinding.rvAllZm.layoutManager = rvLetterLayoutManager
        viewBinding.rvAllZm.adapter = letterAdapter

        //监听滑动事件
        viewBinding.rvAllBrand.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                when (newState) {
                    RecyclerView.SCROLL_STATE_IDLE -> {
                        //当屏幕停止滚动 需要联动
//                        viewModel.changeLetterState(firstVisibleItem)
                    }
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                //获取首个展示和最后一个展示项
                firstVisibleItem =
                    rvBrandAllLayoutManager.findFirstVisibleItemPosition()
                val lastVisibleItem =
                    rvBrandAllLayoutManager.findLastCompletelyVisibleItemPosition()
                changeLetterTitle(firstVisibleItem)
            }
        })

        viewModel.reqFetchSubBrandList()
        viewModel.reqFetchTopBrandFullList()
    }

    override fun scrollToLetter(letter: Char) {
        viewModel.brandAllList.value!!.forEachIndexed {index,letterItem->
            if(letterItem is BrandAllTitleBean &&  letterItem.key.code== letter.code){
                //平顺滑动 但会在底部
//                viewBinding.rvFilterCategory.smoothScrollToPosition(index)
                //指定项滑动到顶部
                rvBrandAllLayoutManager.scrollToPositionWithOffset(index, 0)
                changeLetterTitle(index,true)
                return
            }
        }
    }

    //改变吸顶字母和字母列表状态 ifChangeTitle点击的时候不主动改变标题只通过滚动改变
    private fun changeLetterTitle(position:Int,ifClickChar:Boolean = false){
        if(viewModel.brandAllList.value?.isEmpty()==true){
            return
        }
        if(position<0){
            return
        }
        if(position>=viewModel.brandAllList.value!!.size){
            return
        }
        val bean=viewModel.brandAllList.value!![position]
        var letter = '#'
        if(bean is BrandAllTitleBean){
            letter = bean.key
        }else if(bean is BrandAllBean){
            letter = bean.key
        }
        if(ifClickChar) {
            changeLetterState(letter)
        }else{
            if (letter.toString() != viewBinding.layoutBrandTitle.tvAllBrandTitle.text) {
                viewBinding.layoutBrandTitle.tvAllBrandTitle.text = letter.toString()
                changeLetterState(letter)
            }
        }
    }

    //改变字母状态
    private fun changeLetterState(itemChat:Char?){
        itemChat?.let {chatItem->
            viewModel.brandLetterList.value?.mapIndexed { index, item ->
                if(chatItem.code==item.key.code && !item.ifChecked){
                    item.ifChecked=true
                    letterAdapter.notifyItemRangeChanged(index,1)
                }
                if(chatItem.code != item.key.code && item.ifChecked){
                    item.ifChecked=false
                    letterAdapter.notifyItemRangeChanged(index,1)
                }
            }
        }
    }

    fun hasBrandData():Boolean{
        return viewModel.brandAllList.value?.isNotEmpty()==true
    }
}

interface AllLetterI{
    fun scrollToLetter(letter:Char)//点击Letter后滚动到指定位置
}